package selenium.commons;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SeleniumUtils {

	@Autowired
	private WebDriverWait wait;
	@Autowired
	private WebDriver driver;

	public void waitForObjectAndpopulateIt(String xpath, String sendKeys) {
		if (!sendKeys.equals("")) {
			waitForAElment(xpath);
			driver.findElement(By.xpath(xpath)).sendKeys(sendKeys);
		}
	}

	public Set<String> waitForListAnReturnTextResultSet(String xpath) {

		Set<String> listOfTextValues = new HashSet<String>();

		wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By
				.xpath(xpath)));

		List<WebElement> list = driver.findElements(By.xpath(xpath));

		for (WebElement option : list) {
			String textValue = option.getText();
			if (!"".equals(textValue)) {
				listOfTextValues.add(textValue);
			}
		}
		return listOfTextValues;
	}

	public String waitForObjectAnReturnTextValue(String xpath) {
		waitForAElment(xpath);
		WebElement element = driver.findElement(By.xpath(xpath));
		return element.getText();
	}

	public List<String> waitForListAnReturnAtributes(String xpath,
			String atribute) {

		List<String> listOfAttributes = new ArrayList<String>();

		wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By
				.xpath(xpath)));

		List<WebElement> list = driver.findElements(By.xpath(xpath));

		for (WebElement option : list) {
			listOfAttributes.add(option.getAttribute(atribute));
		}
		return listOfAttributes;
	}

	public void waitForObjectAndClickOnIt(String xpath) {
		waitForAElment(xpath);
		driver.findElement(By.xpath(xpath)).click();
	}

	public void waitNavigator(int someMiliseconds) {
		try {
			Thread.sleep(someMiliseconds);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void pressEnterOn(String xpath) {
		driver.findElement(By.xpath(xpath)).sendKeys(Keys.ENTER);
	}

	public void waitForAElment(String xpath) {
		wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
	}

	public void goToPage(String url) {
		driver.get(url);
	}

	public String getActualPageLink() {
		return driver.getCurrentUrl();
	}

	public void closeDriver() {
		driver.close();
	}

}